#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

void convert_bin_to_c(const char *input_file, const char *output_file, const char *array_name) {
    FILE *in_file = fopen(input_file, "rb");
    if (!in_file) {
        perror("Failed to open input file");
        exit(EXIT_FAILURE);
    }

    FILE *out_file = fopen(output_file, "w");
    if (!out_file) {
        perror("Failed to open output file");
        fclose(in_file);
        exit(EXIT_FAILURE);
    }

    // Write the header of the C file
    fprintf(out_file, "#include <stdint.h>\n\n");
    fprintf(out_file, "const uint8_t %s[] = {\n    ", array_name);

    uint8_t buffer[1024];
    size_t bytes_read;
    size_t count = 0;

    // Read the input file and write the data to the output file
    while ((bytes_read = fread(buffer, 1, sizeof(buffer), in_file)) > 0) {
        for (size_t i = 0; i < bytes_read; ++i) {
            fprintf(out_file, "0x%02X", buffer[i]);
            count++;
            if (count % 16 == 0) {
                fprintf(out_file, ",\n    ");
            } else if (i < bytes_read - 1) {
                fprintf(out_file, ", ");
            }
        }
    }

    // Close the array in the C file
    fprintf(out_file, "\n};\n\n");
    fprintf(out_file, "const uint32_t %s_size = sizeof(%s);\n", array_name, array_name);

    fclose(in_file);
    fclose(out_file);

    printf("Conversion complete! Output written to %s\n", output_file);
}

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <input_file> <output_file> <array_name>\n", argv);
        return EXIT_FAILURE;
    }

    const char *input_file = argv[1];
    const char *output_file = argv[2];
    const char *array_name = argv[3];

    convert_bin_to_c(input_file, output_file, array_name);

    return EXIT_SUCCESS;
}
